package site.luojie.core.factory;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import site.luojie.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description: 代理对象工厂
 * @Author jie.luo
 * @Create: 2020-05-02 08:42
 **/
@Repository
public class ProxyFactory {
//    private ProxyFactory() {
//    }
//
//    public static ProxyFactory proxyFactory = new ProxyFactory();
//
//    public static ProxyFactory getInstance() {
//        return proxyFactory;
//    }

    private TransactionManager transactionManager;

    public Object getJdkProxy(Object object) {
        Object o = Proxy.newProxyInstance(this.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                Object invoke = null;
                try {
                    transactionManager.beginTransaction();

                    invoke = method.invoke(object, args);

                    transactionManager.commitTransaction();
                } catch (Exception e) {
                    e.printStackTrace();
                    transactionManager.rollbackTransaction();
                    throw e;
                }
                return invoke;
            }
        });

        return o;
    }

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
}
